package cn.sharesdk.demo;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import cn.sharesdk.demo.util.Ad;
import cn.sharesdk.facebook.Facebook;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.weibo.TencentWeibo;
import cn.sharesdk.twitter.Twitter;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * 需要sharesdk的支持
 * 
 * @author huangrongcai
 * 
 */
public class MainActivity extends Activity implements OnClickListener {
	private static final String TAG = "MainActivity";
	private static final String FILE_NAME = "/demo.jpg";
	public static String TEST_IMAGE;
	public static String PAR_KEY = "ShareData";
	private boolean silent = false;
	private Context context = this;
	private Button btnButton;
	private Button shareFacebook;
	private Button shareTwitter;
	private Button wechat;
	private Button wechatMoments;
	private Button sina;
	private Button weibo;
	private Button more;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// 初始化
		ShareSDK.initSDK(this);
		initImagePath();
		initViews();

	}

	private void initViews() {
		btnButton = (Button) findViewById(R.id.share);
		shareFacebook = (Button) findViewById(R.id.share_facebook);
		shareTwitter = (Button) findViewById(R.id.share_twitter);
		wechat = (Button) findViewById(R.id.share_wechat);
		wechatMoments = (Button) findViewById(R.id.share_wechatMoments);
		sina = (Button) findViewById(R.id.share_sina);
		weibo = (Button) findViewById(R.id.share_weibo);
		more = (Button) findViewById(R.id.share_more);
		// 监听
		btnButton.setOnClickListener(this);
		shareFacebook.setOnClickListener(this);
		shareTwitter.setOnClickListener(this);
		wechatMoments.setOnClickListener(this);
		wechat.setOnClickListener(this);
		sina.setOnClickListener(this);
		weibo.setOnClickListener(this);
		more.setOnClickListener(this);

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		ShareSDK.stopSDK(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.share:
			goToEditPage(null);
			break;
		case R.id.share_facebook:
			goToEditPage(Facebook.NAME);
			break;
		case R.id.share_twitter:
			goToEditPage(Twitter.NAME);
			break;
		case R.id.share_wechat:
			showdialog();
			break;
		case R.id.share_wechatMoments:
			goToEditPage(WechatMoments.NAME);
			break;
		case R.id.share_sina:
			goToEditPage(SinaWeibo.NAME);
			break;
		case R.id.share_weibo:
			goToEditPage(TencentWeibo.NAME);
			break;
		case R.id.share_more:
			shareMore();
			break;
		default:
			break;
		}

	}

	// 呼出编辑页
	private void goToEditPage(String name) {
		OnekeyShare oks = new OnekeyShare();
		// 分享时Notification的图标和文字
		oks.setNotification(R.drawable.ic_launcher,
				getContext().getString(R.string.app_name));
		oks.setText(getContext().getString(R.string.share_content));

		oks.setImagePath(TEST_IMAGE);
		oks.setSilent(silent);
		oks.setTitle("分享到qq空间，标题必要字段");
		oks.setTitleUrl("http://sharesdk.cn/");
		// site是分享此内容的网站名称，仅在QQ空间使用
		oks.setSite(context.getString(R.string.app_name));
		// siteUrl是分享此内容的网站地址，仅在QQ空间使用
		oks.setSiteUrl("http://sharesdk.cn");
		if (name != null) {
			oks.setPlatform(name);// 如果已选择平台，则直接呼出编辑页了
		}
		oks.show(getContext());
	}

	/**
	 * 分享更多，选择性的广播分享，分享中将收集当前手机的包名信息，依据包名，过滤不不需要的平台，或是根据平台，指定有区别的分享内容
	 */
	private void shareMore() {
		String contentDetails = "分享详细内容";
		String contentBrief = "分享简单内容";
		String shareUrl = "网络资源有？";
		Intent shareInt = new Intent(Intent.ACTION_SEND);
		shareInt.setType("text/plain");
		
		List<ResolveInfo> resInfo = getPackageManager().queryIntentActivities(
				shareInt, 0);

		if (!resInfo.isEmpty()) {
			List<Intent> targetedShareIntents = new ArrayList<Intent>();

			for (ResolveInfo info : resInfo) {
				
				Intent targeted = new Intent(Intent.ACTION_SEND);
				targeted.setType("image/*");
				targeted.setType("text/plain");
				
				targeted.putExtra(Intent.EXTRA_SUBJECT, "标题");
				targeted.putExtra(Intent.EXTRA_TEXT, contentDetails);
				targeted.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				
				targeted.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(TEST_IMAGE)));
				
				ActivityInfo activityInfo = info.activityInfo;
				// judgments : activityInfo.packageName, activityInfo.name, etc.
				if (activityInfo.packageName.contains("bluetooth")
						|| activityInfo.name.contains("bluetooth")) {
					targeted.putExtra(Intent.EXTRA_TEXT, "这个文本交给小蓝牙分享");
				}
				if (activityInfo.packageName.contains("WBlog")
						|| activityInfo.name.contains("bluetooth")) {
					targeted.putExtra(Intent.EXTRA_TEXT, "这个文本交给微信分享");
				}
				if (activityInfo.packageName.contains("gm")
						|| activityInfo.name.contains("email")) {
					targeted.putExtra(Intent.EXTRA_TEXT, "这个给小邮"+contentDetails);
				}
				targeted.setPackage(activityInfo.packageName);
				targetedShareIntents.add(targeted);
			}
			Intent chooserIntent = Intent.createChooser(
					targetedShareIntents.remove(0), "选择平台Select app to share");
			chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
					targetedShareIntents.toArray(new Parcelable[] {}));
			  startActivity(chooserIntent);
		}

	}

	// 针对微信同一平台不同分享类型，弹出一个选择对话框（可选)
	public void showdialog() {
		Builder builder = new AlertDialog.Builder(getContext());
		builder.setTitle(getContext().getString(R.string.share));
		String[] items = { getContext().getString(R.string.wechatmoments),
				getContext().getString(R.string.wechat) };
		builder.setItems(items, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case 0:
					goToEditPage(WechatMoments.NAME);
					break;
				case 1:

					goToEditPage(Wechat.NAME);
					break;
				default:
					break;
				}

			}
		});
		builder.show();

	}

	/**
	 * 获取本地图片路径
	 */
	private void initImagePath() {
		try {
			if (Environment.MEDIA_MOUNTED.equals(Environment
					.getExternalStorageState())
					&& Environment.getExternalStorageDirectory().exists()) {
				TEST_IMAGE = Environment.getExternalStorageDirectory()
						.getAbsolutePath() + FILE_NAME;
			} else {
				TEST_IMAGE = getApplication().getFilesDir().getAbsolutePath()
						+ FILE_NAME;
			}
			File file = new File(TEST_IMAGE);
			if (!file.exists()) {
				file.createNewFile();
				Bitmap pic = BitmapFactory.decodeResource(getResources(),
						R.drawable.demo);
				FileOutputStream fos = new FileOutputStream(file);
				pic.compress(CompressFormat.JPEG, 100, fos);
				fos.flush();
				fos.close();
			}
		} catch (Throwable t) {
			t.printStackTrace();
			TEST_IMAGE = null;
		}
	}

	private Activity getContext() {
		return this;
	}

}
